package com.offcn.filter;

import com.alibaba.fastjson.JSON;
import com.offcn.pojo.User;
import com.offcn.util.ResultVo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter("/*")
//登录权限拦截过滤器
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求的url地址
        String uri = request.getRequestURI();
        //获取请求的方法
        String key = request.getParameter("key");
        if (uri.equals("/") || uri.equals("/index.jsp") || uri.equals("/favicon.icon") ||
                uri.equals("/code") || key.equals("login") || key.equals("loginOut")||uri.equals("/index")) {
            filterChain.doFilter(request, response);
        } else {
            //验证是否登录
            HttpSession session = request.getSession();
            Object loginUser = session.getAttribute("loginUser");
            if (loginUser==null){
                //没有登录
            ResultVo vo = new ResultVo(500, "请先登录后操作", null);
            response.getWriter().write(JSON.toJSONString(vo));
            }else {
                //直接放行
                filterChain.doFilter(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
